package itstudio.instructor.ui;

import itstudio.app.wq.R;
import itstudio.instructor.adapter.NewsListAdapterNoHead;
import itstudio.instructor.config.Config;
import itstudio.instructor.config.ImageOptionsUtil;
import itstudio.instructor.config.MyApplication;
import itstudio.instructor.entity.News;
import itstudio.instructor.entity.User;
import itstudio.instructor.http.TwitterRestClient;
import itstudio.instructor.util.LoginUtil;
import itstudio.instructor.util.ToastUtil;
import itstudio.instructor.widget.PullScrollView;
import itstudio.instructor.xlistview.XListView;
import itstudio.instructor.xlistview.XListView.IXListViewListener;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.Header;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

public class UserDetailActivity extends Activity implements
		IXListViewListener, PullScrollView.OnTurnListener {
	private XListView xListView;
	private NewsListAdapterNoHead adapter;
	private List<News> newsList  = new ArrayList<News>();;
	private PullScrollView mScrollView;
	private ImageView mHeadImg;
	private LinearLayout back_layout;
	private TextView userinfo_title;
	private Button bt_follow;
	private User user = new User();
	protected ImageLoader imageLoader = ImageLoader.getInstance();
	protected DisplayImageOptions options;
	private int page=0;
    private LinearLayout loadLayout;
    private LinearLayout loadNodataLayout;
    
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_teacher_detail);
		options = ImageOptionsUtil.headImageOptions();
		findViewById();
		setOnclick();
		initView();
	}

	protected void findViewById() {
		back_layout = (LinearLayout) findViewById(R.id.instructor_detail_back_layout);
		bt_follow = (Button) findViewById(R.id.bt_jiaguanzhu);
		TextView name_tv = (TextView) findViewById(R.id.name_tv);
		TextView fansnum_tv = (TextView) findViewById(R.id.fans_num);
		TextView follownum_tv = (TextView) findViewById(R.id.follow_num);
		TextView newsnum_tv = (TextView) findViewById(R.id.news_num);
		TextView intro_tv = (TextView) findViewById(R.id.intro_tv);
		userinfo_title=(TextView) findViewById(R.id.userinfo_title);
		ImageView headImg = (ImageView) findViewById(R.id.headImg);
		Intent intent = getIntent();
		user = (User) intent.getExtras().get("user");
		name_tv.setText(user.getName());
		fansnum_tv.setText(user.getFansNum().toString());
		follownum_tv.setText(user.getFollowNum().toString());
		newsnum_tv.setText(user.getNewsNum().toString());
		intro_tv.setText(user.getIntro());
		if(user.getStatus()==User.STATUS_TREACHER){
			userinfo_title.setText(R.string.instructor);
		}else if (user.getStatus()==User.STATUS_PUBLIC) {
			userinfo_title.setText(R.string.public_num);
			
		}
			
		
		if(user.isFocus()){
			bt_follow.setSelected(true);
			bt_follow.setText(R.string.follow_cancel);
		}
		imageLoader.displayImage(Config.HEAD_URL +user.getHeadUrl(),
				headImg, options);
		
		loadLayout = (LinearLayout) findViewById(R.id.view_loading);
		loadNodataLayout = (LinearLayout) findViewById(R.id.view_load_nodata);

	}

	protected void setOnclick() {
		MyOnClick onclick = new MyOnClick();
		back_layout.setOnClickListener(onclick);
		bt_follow.setOnClickListener(onclick);

	}

	class MyOnClick implements OnClickListener {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.instructor_detail_back_layout:
				finish();
				break;
			case R.id.bt_jiaguanzhu:
				
				if (bt_follow.isSelected()) {
					
					final Button btn = bt_follow;
					cancelFollow(user.getId(),btn);

				} else {
					
					final Button btn = bt_follow;
					addFollow(user.getId(),btn);
				}

				break;

			default:
				break;
			}

		}

	}

	// 填充listview
	protected void initView() {
		
		mScrollView = (PullScrollView) findViewById(R.id.scroll_view);
		mHeadImg = (ImageView) findViewById(R.id.background_img);
		mScrollView.smoothScrollTo(0, 20);
		mScrollView.setHeader(mHeadImg);
		mScrollView.setOnTurnListener(this);
		xListView = (XListView) findViewById(R.id.xlist_test);
		xListView.setPullLoadEnable(true);
		xListView.setPullRefreshEnable(false);// 取消下拉刷新

		
		adapter = new NewsListAdapterNoHead(UserDetailActivity.this, newsList,R.layout.listitem_news_no_head);
		xListView.setAdapter(adapter);
		xListView.setXListViewListener(this);
		xListView.setOnItemClickListener(new OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int position,
					long arg3) {

				TextView title=(TextView) arg1.findViewById(R.id.list_item_title);
				title.setTextColor(getResources().getColor(R.color.light_black));
				
				Intent intent = new Intent();
				intent.setClass(UserDetailActivity.this, NewsDetailActivity.class);
				News news = (News) adapter.getItem(position-1); 
				news.setUser(user);//必须手动设置
				intent.putExtra("news", news);
				startActivity(intent);
				
			}
		});
		setListViewHeightBasedOnChildren(xListView);// 解决listview与scrollview冲突问题
		if(user.getStatus()!=0){
			loadNews();
		}
		

	}

	// 解决listview与scrollview冲突问题
	private void setListViewHeightBasedOnChildren(ListView xListView) {

		ListAdapter listAdapter = xListView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, xListView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = xListView.getLayoutParams();
		params.height = totalHeight
				+ (xListView.getDividerHeight() * (listAdapter.getCount() - 1));
		xListView.setLayoutParams(params);
	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		Handler mHandler = new Handler();
		mHandler.postDelayed(new Runnable() {
			@Override
			public void run() {
				onLoad();
				// mAdapter.notifyDataSetChanged();
			}
		}, 2000);

	}
	//加载news 
	private void loadNews(){
		RequestParams params = new RequestParams();
		params.put("page", page+1);
		params.put("user.id", user.getId());
		TwitterRestClient.post(Config.AC_NEWS_PERSON, params, new AsyncHttpResponseHandler(){
			
			@Override
			public void onStart() {
				super.onStart();

			}
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
				onLoad();
				loadLayout.setVisibility(View.GONE);
				loadNodataLayout.setVisibility(View.VISIBLE);
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] data) {
				//加载成功
				loadLayout.setVisibility(View.GONE);
				loadNodataLayout.setVisibility(View.GONE);
				onLoad();
				String response = new String(data);
				if(response!=null && response.length()>5){
					
					Gson gson = new GsonBuilder()  
					.setDateFormat("yyyy-MM-dd HH:mm:ss")  
					.create();
					newsList  = gson.fromJson(response , new TypeToken<List<News>>(){}.getType());
					adapter.appendToList(newsList);
					page= page+1;
				}
				onLoad();
				if(adapter.getCount()==0){
					loadNodataLayout.setVisibility(View.VISIBLE);
				}
				if(newsList!=null  && newsList.size()==10){
					xListView.setPullLoadEnable(true);
					page =page+1;
				}
				else{
					xListView.setPullLoadEnable(false);
				}
				setListViewHeightBasedOnChildren(xListView);
			}});
	}
	private void addFollow(String id,final Button btn){
		
		
		if(MyApplication.user==null){
			
			ToastUtil.showInfoMsg(UserDetailActivity.this, R.string.please_login);
			return;
		}
		RequestParams params = new RequestParams();
		params.put("follow.startId", id);
		TwitterRestClient.post(Config.AC_FOLLOW_ADD, params, new AsyncHttpResponseHandler(){
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				//加载成功
				String result = new String(arg2);
	
				if(result.indexOf("success")!=-1){
					btn.setSelected(true);
					btn.setTextColor(Color.WHITE);
					btn.setText(R.string.follow_cancel);
					MyApplication.user.setFollowNum(MyApplication.user.getFollowNum()+1);
				}
				if(result.indexOf("login")!=-1){
					LoginUtil.Login(UserDetailActivity.this);
				}
			}});
	}
	private void cancelFollow(String id,final Button btn){
		
		RequestParams params = new RequestParams();
		params.put("follow.startId", id);
		TwitterRestClient.post(Config.AC_FOllOW_CANCEL, params, new AsyncHttpResponseHandler(){
			
			@Override
			public void onFailure(int arg0, Header[] arg1, byte[] arg2,
					Throwable arg3) {
				// TODO Auto-generated method stub
			}
			
			@Override
			public void onSuccess(int arg0, Header[] arg1, byte[] arg2) {
				//加载成功
				String result = new String(arg2);
				
				if(result.indexOf("success")!=-1){
					btn.setSelected(false);
					btn.setTextColor(Color.BLACK);
					btn.setText(R.string.follow);
					MyApplication.user.setFollowNum(MyApplication.user.getFollowNum()-1);
				}
				if(result.indexOf("login")!=-1){
					LoginUtil.Login(UserDetailActivity.this);
				}
			}});
	}
	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		loadNews();

	}

	private void onLoad() {
		xListView.stopRefresh();
		xListView.stopLoadMore();
	}

	@Override
	public void onTurn() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onScrollChanged(PullScrollView scrollView, int x, int y,
			int oldx, int oldy) {

	}

}
